package io.zerous.engine

import android.view.KeyEvent
import android.view.View
import io.zerous.engine.utils.Pool

/**
 * Created by Zerous on 2018/2/28.
 */
class KeyHandler(view: View) : View.OnKeyListener {
    val pressedKeys = BooleanArray(128)
    val keyEventPool = Pool(100) {
        Input.KeyEvent()
    }

    val keyEventsBuffer = ArrayList<Input.KeyEvent>()
    val keyEvents = ArrayList<Input.KeyEvent>()
    get() = synchronized(this) {
        for (i in field)
            keyEventPool.free(i)
        field.clear()
        field.addAll(keyEventsBuffer)
        keyEventsBuffer.clear()
        field
    }

    init {
        view.setOnKeyListener(this)
        view.isFocusableInTouchMode = true
        view.requestFocus()
    }

    override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.action == android.view.KeyEvent.ACTION_MULTIPLE)
            return false



        synchronized(this) {
            val keyEvent = keyEventPool.newObject()
            keyEvent.keyCode = keyCode
            keyEvent.keyChar = event?.unicodeChar?.toChar()!!
            if (event.action == android.view.KeyEvent.ACTION_DOWN) {
                keyEvent.type = KEY_DOWN
                if (keyCode in 0..127)
                    pressedKeys[keyCode] = true
            }
            if (event.action == android.view.KeyEvent.ACTION_UP) {
                keyEvent.type = KEY_UP
                if (keyCode in 0..127)
                    pressedKeys[keyCode] = false
            }
            keyEventsBuffer.add(keyEvent)
        }
        return false
    }

    fun isKeyPressed(keyCode: Int): Boolean {
        if (keyCode !in 0..127)
            return false
        return pressedKeys[keyCode]
    }
}